package com.android.jumishangcheng.fragment.detail;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.jumishangcheng.model.group.MainThematicActivity_Insert;
import com.android.jumishangcheng.R;
import com.android.jumishangcheng.activity.BaseObject;
import com.android.jumishangcheng.fragment.BaseLazyFragment;
import com.android.jumishangcheng.model.detail.BrandGoodsListData;
import com.android.jumishangcheng.model.detail.BrandGoodsListDataCallback;
import com.android.jumishangcheng.model.group.AdPictureData;
import com.android.jumishangcheng.model.group.AdPictureDataCallback;
import com.android.jumishangcheng.model.group.BrandClearanceCallback;
import com.android.jumishangcheng.model.group.BrandClearanceData;
import com.android.jumishangcheng.model.group.MainThematicActivity_InsertCallback;
import com.android.jumishangcheng.utils.ConstantsUrl;
import com.android.jumishangcheng.utils.HttpUtils;
import com.android.jumishangcheng.utils.MyLog;
import com.android.jumishangcheng.utils.ObjectUtils;
import com.android.jumishangcheng.view.group.VRefreshLayout;
import com.android.jumishangcheng.view.recycleview.CustomLoadMoreView;
import com.android.jumishangcheng.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/5.
 */

public class Fragment_BClearance_TabList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private String sort;
    private String cid;
    private int page;
    private BrandGoodsListData branddata = new BrandGoodsListData();
    private ArrayList<BrandClearanceData.DataBean.ListBean> listdata = new ArrayList<>();
    private ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert = new ArrayList<>();
    private View inflate;
    private TextView refresh_textView;
    private int coming_count = 0;
    private TextView kill_hour;
    private TextView kill_minute;
    private TextView kill_second;
    private ImageView bclearance_head_banner_iv1;
    private ImageView bclearance_head_banner_iv2;
    private ImageView bclearance_head_banner_iv3;
    private boolean isRunning = true;
    private int time;
    private View fragment_head;
    private LinearLayout bclearance_head_banner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                if (time > 0) {
                    String hour = String.format("%02d", time / 3600);
                    String minute = String.format("%02d", time % 3600 / 60);
                    String second = String.format("%02d", time % 60);
                    kill_hour.setText(hour);
                    kill_minute.setText(minute);
                    kill_second.setText(second);
                    time--;
                }
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        // coming_count++;

    }

    public static Fragment_BClearance_TabList newInstance(int time, String cid, String sort) {
        Fragment_BClearance_TabList fragment = new Fragment_BClearance_TabList();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, time);
        args.putString(ARG_PARAM2, cid);
        args.putString(ARG_PARAM3, sort);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
            getMianThematic_Insert();
            GetDataAdPic();
            GetListData(page);
            initRecycle();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_bdmainrefresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        fragment_head = inflater.inflate(R.layout.bclearance_tablist_head_banner, null, false);
        kill_hour = (TextView) fragment_head.findViewById(R.id.kill_hour);
        kill_minute = (TextView) fragment_head.findViewById(R.id.kill_minute);
        kill_second = (TextView) fragment_head.findViewById(R.id.kill_second);
        if (getArguments() != null) {
            time = getArguments().getInt(ARG_PARAM1);
            cid = getArguments().getString(ARG_PARAM2);
            sort = getArguments().getString(ARG_PARAM3);
            new Thread() {
                @Override
                public void run() {
                    while (isRunning) {
                        SystemClock.sleep(1000);
                        handler1.sendEmptyMessage(1);
                    }
                }
            }.start();
        }
        mainTopBg.setVisibility(View.GONE);
        //  initHeadSort(goodsData);
        return rootView;
    }

    private void initRecycle() {
        String hour = String.format("%02d", time / 3600);
        String minute = String.format("%02d", time % 3600 / 60);
        String second = String.format("%02d", time % 60);
        kill_hour.setText(hour);
        kill_minute.setText(minute);
        kill_second.setText(second);
        bclearance_head_banner = (LinearLayout) fragment_head.findViewById(R.id.bclearance_head_banner);
        bclearance_head_banner_iv1 = (ImageView) fragment_head.findViewById(R.id.bclearance_head_banner_iv1);
        bclearance_head_banner_iv2 = (ImageView) fragment_head.findViewById(R.id.bclearance_head_banner_iv2);
        bclearance_head_banner_iv3 = (ImageView) fragment_head.findViewById(R.id.bclearance_head_banner_iv3);
        adapter = new AdaptList(mcontext, ta_insert, listdata, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(fragment_head);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
//                switch (view.getId()) {
//                    case R.id.bdmain_iv:
//
//                        GetBrandGoodsList(listdata.get(position).getId());
//                        break;
//                }
                return false;
            }
        });
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                getMianThematic_Insert();
                                GetDataAdPic();
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                getMianThematic_Insert();
                GetDataAdPic();
                GetListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
//        getMianThematic_Insert();
//        GetDataAdPic();
        GetListData(page);
    }

    /**
     * 专题活动插入信息
     */
    private void getMianThematic_Insert() {
        String address = ConstantsUrl.domain + ConstantsUrl.MAINTHMATIC_INSERT;
        HashMap<String, String> map = new HashMap<>();
        map.put("posid", "5");
        HttpUtils.get(address, map, new MainThematicActivity_InsertCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(MainThematicActivity_Insert response, int id) {
                ta_insert.clear();
                if (response == null) {
                    return;
                }
                MainThematicActivity_Insert.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getList())) {
                    ta_insert.addAll(data.getList());
                    adapter.setTa_insert(ta_insert);
                    mRecyclerView.setLayoutManager(mLayoutManager);
                    mRecyclerView.setAdapter(adapter);
                }
            }
        });
    }

    /**
     * 广告图
     */
    private void GetDataAdPic() {
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        MyLog.e("地址", address);
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", "15");
        HttpUtils.get(address, map, new AdPictureDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(AdPictureData response, int id) {
                if (response == null) {
                    return;
                }
                AdPictureData.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getAd())) {
                    List<AdPictureData.DataBean.AdBean> adBeen = data.getAd();
                    int size = adBeen.size();
                    if (size > 0) {
                        ObjectUtils.photo2(mcontext, adBeen.get(0).getPath(), bclearance_head_banner_iv1);
                        if (size > 1) {
                            ObjectUtils.photo2(mcontext, adBeen.get(1).getPath(), bclearance_head_banner_iv2);
                            if (size > 2) {
                                ObjectUtils.photo2(mcontext, adBeen.get(2).getPath(), bclearance_head_banner_iv3);
                            }
                        }
                    }else {
                        bclearance_head_banner.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private void GetBrandGoodsList(final String top) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.BRANDGOODSLIST;
        HashMap<String, String> map = new HashMap<>();

        map.put("top", top + "");
        if (networkConnected) {
            HttpUtils.get(address, map, new BrandGoodsListDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(BrandGoodsListData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        BrandGoodsListData.DataBean data = response.getData();
                        if (data != null && ObjectUtils.listHasData(data.getBrand_list())) {
//                           ArrayList< BrandGoodsListData.DataBean.Brand_list> brand_list = new ArrayList<BrandGoodsListData.DataBean.Brand_list>();
//                            brand_list.addAll(response.getData().getBrand_list());
                            //   MyLog.e("brand_listdd",branddata.getData().getBrand_list().size()+"");
//                            branddata.setData(response.getData());
//                            branddata.setCode(response.getCode());
//                            branddata.setMsg(response.getMsg());
//                            branddata.setTime(response.getTime());
//                            branddata.setFlag(response.getFlag());
//                            branddata.getData().setBrand_list(brand_list);
//                            branddata.getData().getRow().setCatname(response.getData().getRow().getCatname());
//                            branddata.getData().getRow().setThumb(response.getData().getRow().getThumb());
//                            branddata.getData().getRow().setTop(response.getData().getRow().getTop());
                            Intent intent_bd = new Intent(mcontext, BaseObject.class);
                            intent_bd.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "品牌商品列表");
                            intent_bd.putExtra("catname", data.getRow().getCatname());
                            intent_bd.putExtra("top", top);
                            startActivity(intent_bd);
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }

    private void GetListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.BRANDCLEARANCE;
            HashMap<String, String> map = new HashMap<>();
            map.put("page", page + "");
            map.put("sort", sort);
            map.put("order", "goods_id");
            map.put("cid", cid);
            HttpUtils.get(address, map, new BrandClearanceCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(BrandClearanceData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        BrandClearanceData.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                        List<BrandClearanceData.DataBean.ListBean> list = data.getList();
                        if (page == 1) {
                            listdata.clear();
                            listdata.addAll(list);
                            adapter.setNewData(listdata);
                            mRecyclerView.setLayoutManager(mLayoutManager);
                            mRecyclerView.setAdapter(adapter);
                        } else {
                            listdata.addAll(list);
                            adapter.addData(list);
                            adapter.loadMoreComplete();
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<BrandClearanceData.DataBean.ListBean, BaseViewHolder> {
        private int limitposition;
        private ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert;

        public AdaptList(Context context, ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert, ArrayList<BrandClearanceData.DataBean.ListBean> data, String type) {
            super(data);
            this.ta_insert = ta_insert;
            addItemType(ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE, R.layout.item_list_main);
        }

        public ArrayList<MainThematicActivity_Insert.DataBean.ListBean> getTa_insert() {
            return ta_insert;
        }

        public void setTa_insert(ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert) {
            this.ta_insert = ta_insert;
            limitposition = 3 * ta_insert.size();
        }

        @Override
        protected void convert(BaseViewHolder holder, final BrandClearanceData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE:
                    ((TextView) holder.getView(R.id.item_list_sort_aa_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(mContext, mainlistdata.getImg_src(), ((ImageView) holder.getView(R.id.main_list_item_image)));
                    // Float discount = Float.parseFloat(mainlistdata.getTeam_price())/Float.parseFloat(mainlistdata.getPrice());
                    // holder.setText(R.id.main_list_item_count, new DecimalFormat(".0").format(discount) + "折");
                    holder.setText(R.id.main_list_item_tuannumber, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_start_soon_num, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_free_num, mainlistdata.getTeam_num() + "人团");
                    int sell = mainlistdata.getSell();
                    if (sell > 0) {
                        holder.setText(R.id.main_list_item_alltuannumber2, "已团" + sell + "件");
                    }
                    holder.setText(R.id.main_list_item_title, mainlistdata.getName());
                    String price1 = mainlistdata.getTeam_price();
                    SpannableString msp = new SpannableString("￥" + price1);
                    msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.setText(R.id.main_list_item_money_after, msp);
                    /**
                     * 插入专题活动
                     */
                    final int taposition = holder.getAdapterPosition();
                    if (mcontext instanceof FragmentActivity) {
                        if (taposition % 3 == 0 && taposition < limitposition && ta_insert.size() > 0) {

                            holder.getView(R.id.ll_tainsert).setVisibility(View.VISIBLE);
                            holder.getView(R.id.progress_hot).setVisibility(View.INVISIBLE);
                            TextView more_tv = (TextView) holder.getView(R.id.more_tv);
                            TextView hotactivity_title = (TextView) holder.getView(R.id.hotactivity_title);
                            hotactivity_title.setText(ta_insert.get(taposition / 3 - 1).getName());
                            //水平滚动列表
                            NestFullListView tabrow = (NestFullListView) holder.getView(R.id.grid);
                            //        //动态设置选项卡宽度，超过2个可以滑动查看
                            DisplayMetrics metrics = new DisplayMetrics();
                            mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                            int width = (int) (metrics.widthPixels / 2.5);
                            final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
                            tabrow.setAdapter(new NestFullListViewAdapter<MainThematicActivity_Insert.DataBean.ListBean.ApplyBean>(R.layout.list_main_hor_adapter, ta_insert.get(taposition / 3 - 1).getApply_list()) {
                                @Override
                                public void onBind(int position, MainThematicActivity_Insert.DataBean.ListBean.ApplyBean testBean, NestFullViewHolder holder) {
                                    (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                    String price1 = testBean.getTeam_price();
                                    SpannableString msp = new SpannableString("￥" + price1);
                                    msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                                    holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());
                                    holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                                    ObjectUtils.photo2(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));

                                }
                            });

                            tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                                @Override
                                public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                                    ObjectUtils.ToDetailActivity(mcontext, 1, ta_insert.get(taposition / 3 - 1).getApply_list().get(pos).getGoods_id(), "");
                                }
                            });
                            more_tv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(mcontext, BaseObject.class);
                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, ta_insert.get(taposition / 3 - 1).getId());
                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "专题活动");
                                    mcontext.startActivity(intent);
                                }
                            });

                        } else {
                            holder.getView(R.id.ll_tainsert).setVisibility(View.GONE);
                        }
                    }

                    holder.addOnClickListener(R.id.main_list_item_go_kai)
                            .addOnClickListener(R.id.ll_free)
                            .addOnClickListener(R.id.ll_start_soon)
                            .addOnClickListener(R.id.ll_result);
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }
}
